//
//  SettingViewController.m
//  FDSMeshLibDemo
//
//  Created by LEIPENG on 2022/6/10.
//

#import "SettingViewController.h"
#import "ResetViewController.h"

#define MESH_FOLDER     @"MESH_FOLDER"
#define MESH_FILE       @"MESH"
#define LOG_FILE_NAME   @"FDS_SDKLogData.txt"

@interface SettingViewController ()<UITableViewDataSource, UITableViewDelegate, UIDocumentInteractionControllerDelegate>

@property (nonatomic, strong) MeshTool *meshTool;
@property (weak, nonatomic) IBOutlet UITableView *tableview;
@property (nonatomic, strong) UIDocumentInteractionController *documentInteractionController;

@end

@implementation SettingViewController

#pragma mark - Initialize
- (void)InitializeCode{
    self.title = @"设置";
    self.meshTool = [MeshTool shareInstance];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self InitializeCode];
}
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 8;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] ;
    }
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (indexPath.row == 0) {
        cell.textLabel.text = @"MESH库版本";
        cell.detailTextLabel.text = [NSString stringWithFormat:@"V: %@",[FDSMeshApi getVersion]];
    } else if (indexPath.row == 1) {
        cell.textLabel.text = @"关于软件";
        NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
        NSString *app_version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
        NSString *build_version = [infoDictionary objectForKey:@"CFBundleVersion"];
        cell.detailTextLabel.text = [NSString stringWithFormat:@"V: %@(%@)",app_version, build_version];
    } else if (indexPath.row == 2) {
        cell.textLabel.text = @"分享数据";
        cell.detailTextLabel.text = @"";
    } else if (indexPath.row == 3) {
        cell.textLabel.text = @"查看日志";
        cell.detailTextLabel.text = @"";
    } else if (indexPath.row == 4) {
        cell.textLabel.text = @"清空日志";
        cell.detailTextLabel.text = @"";
    } else if (indexPath.row == 5) {
        cell.textLabel.text = @"使用FastProvision";
        cell.detailTextLabel.text = self.meshTool.meshModel.isFastProvision ? @"YES" : @"NO";
    } else if (indexPath.row == 6) {
        cell.textLabel.text = @"兼容旧版订阅组";
        cell.detailTextLabel.text = self.meshTool.meshModel.isCompatibleSubscribe ? @"YES" : @"NO";
    } else if (indexPath.row == 7) {
        cell.textLabel.text = @"重置设备";
        cell.detailTextLabel.text = @"";
    }
    return cell;
}
#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 2) {
        [self shareMeshInfo];
    } else if (indexPath.row == 3) {
        [self checkLogInfo];
    } else if (indexPath.row == 4) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"清空日志？" message:nil preferredStyle:(UIAlertControllerStyleAlert)];
        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {}]];
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            [FDSMeshApi clearSdkLog];
            [SVProgressHUD showSuccessWithStatus:@"清空日志成功！"];
        }]];
        [self presentViewController:alert animated:YES completion:nil];
    } else if (indexPath.row == 5) {
        UIAlertController *sheetAlert = [UIAlertController alertControllerWithTitle:@"使用FastProvision？" message:nil preferredStyle:(UIAlertControllerStyleActionSheet)];
        [sheetAlert addAction:[UIAlertAction actionWithTitle:@"YES" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            self.meshTool.meshModel.isFastProvision = YES;
            [self.meshTool codingMeshData:self.meshTool.meshModel];
            [self.tableview reloadData];
        }]];
        [sheetAlert addAction:[UIAlertAction actionWithTitle:@"NO" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            self.meshTool.meshModel.isFastProvision = NO;
            [self.meshTool codingMeshData:self.meshTool.meshModel];
            [self.tableview reloadData];
        }]];
        [sheetAlert addAction:[UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {}]];
        if (DEVICE_ISIPAD) {
            sheetAlert.popoverPresentationController.sourceView = self.view;
            sheetAlert.popoverPresentationController.sourceRect = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
        }
        [self presentViewController:sheetAlert animated:YES completion:nil];
    } else if (indexPath.row == 6) {
        UIAlertController *sheetAlert = [UIAlertController alertControllerWithTitle:@"是否兼容旧版订阅组？" message:nil preferredStyle:(UIAlertControllerStyleActionSheet)];
        [sheetAlert addAction:[UIAlertAction actionWithTitle:@"YES" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            self.meshTool.meshModel.isCompatibleSubscribe = YES;
            [self.meshTool codingMeshData:self.meshTool.meshModel];
            [self.tableview reloadData];
        }]];
        [sheetAlert addAction:[UIAlertAction actionWithTitle:@"NO" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            self.meshTool.meshModel.isCompatibleSubscribe = NO;
            [self.meshTool codingMeshData:self.meshTool.meshModel];
            [self.tableview reloadData];
        }]];
        [sheetAlert addAction:[UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {}]];
        if (DEVICE_ISIPAD) {
            sheetAlert.popoverPresentationController.sourceView = self.view;
            sheetAlert.popoverPresentationController.sourceRect = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
        }
        [self presentViewController:sheetAlert animated:YES completion:nil];
    } else if (indexPath.row == 7) {
        ResetViewController *viewController = [[ResetViewController alloc] init];
        [self.navigationController pushViewController:viewController animated:YES];
    }
}

#pragma mark - Log
- (void)checkLogInfo{
    NSString *documentPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString * filePath = [documentPath stringByAppendingPathComponent:LOG_FILE_NAME];
    if ([fileManager fileExistsAtPath:filePath]){
        self.documentInteractionController = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:filePath]];
        self.documentInteractionController.delegate = self;
        [self.documentInteractionController presentPreviewAnimated:YES];
    }
}

#pragma mark - Share
- (void)shareMeshInfo{
    NSString *dicJson = [FDSMeshApi getCurrentMeshJson];
    NSString * filePath = [self writeToFile:dicJson];
    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]){
        self.documentInteractionController = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:filePath]];
        self.documentInteractionController.delegate = self;
        [self.documentInteractionController presentPreviewAnimated:YES];
    }
}
- (NSString *)writeToFile:(NSString *)text{
    NSString * filePath = [self getFilePath];
    if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]){
        [text writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    }
    return filePath;
}
- (NSString *)getFilePath{
    [self creatFolder];
    NSString *document = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *folder = [document stringByAppendingPathComponent:MESH_FOLDER];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat=@"yyyyMMddHHmmssSSS";
    NSString * dateString = [NSString stringWithFormat:@"%@",[dateFormatter stringFromDate:[NSDate date]]];
    NSString *filePath=[folder stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_%@.txt",MESH_FILE,dateString]];
    return filePath;
}
- (void)creatFolder{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *document = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *folder = [document stringByAppendingPathComponent:MESH_FOLDER];
    if (![fileManager fileExistsAtPath:folder]){
        [fileManager createDirectoryAtPath:folder withIntermediateDirectories:NO attributes:nil error:NULL];
    }
}
- (void)deleteFile{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *document = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *folder = [document stringByAppendingPathComponent:MESH_FOLDER];
    if ([[NSFileManager defaultManager] fileExistsAtPath:folder]){
        NSArray *fileList=[fileManager contentsOfDirectoryAtPath:folder error:NULL];
        for (NSString *filePath in fileList) {
            NSString *deletePath = [folder stringByAppendingPathComponent:filePath];
            if ([[NSFileManager defaultManager] fileExistsAtPath:deletePath]){
                [[NSFileManager defaultManager] removeItemAtPath:deletePath error:NULL];
            }
        }
    }
}
#pragma mark - UIDocumentInteractionControllerDelegate
- (UIViewController *)documentInteractionControllerViewControllerForPreview:( UIDocumentInteractionController *)interactionController{
    return self;
}
- (void)documentInteractionControllerWillBeginPreview:(UIDocumentInteractionController *)controller{
    // NSLog(@"开始调用文件分享功能");
}
- (void)documentInteractionControllerDidEndPreview:(UIDocumentInteractionController *)controller{
    // NSLog(@"结束调用文件分享功能");
}

@end
